<script setup lang="ts">
import { computed, ref } from 'vue'
import { uuid } from '../Utils'
import { useTodoStore } from '../Storage'

const store = useTodoStore()

const todos = store.state.todos
const newTodo = ref('')
function addNewTodo(e: KeyboardEvent) {
  if (e.key !== 'Enter' || newTodo.value.trim() === '') return
  store.addTodo({
    uuid: uuid(),
    text: newTodo.value.trim(),
    done: false,
  })
  newTodo.value = ''
}

const allDone = computed({
  get: () => {
    if (
      todos.length > 0 &&
      todos.filter(t => t.done).length === todos.length
    ) {
      return true
    }
    return false
  },
  set(val: boolean) {
    todos.forEach(t => (t.done = val))
  },
})
</script>

<template>
  <div class="new-todo">
    <input class="toggle-all" type="checkbox" v-model="allDone" />
    <input class="new-todo-input" type="text" autofocus autocomplete="off" placeholder="你想做什么呢？"
      v-model="newTodo" :onKeyup="addNewTodo" />
  </div>
</template>
